package com.wgh.demo.ai.factory;

import com.wgh.demo.ai.config.AiModelConfig;
import com.wgh.demo.ai.enums.AiModelType;
import com.wgh.demo.ai.service.AiModelService;
import com.wgh.demo.ai.service.impl.AlibabaAiModelServiceImpl;
import com.wgh.demo.ai.service.impl.DeepSeekAiModelServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

@Component
public class AiModelFactory {
    private final Map<String, AiModelService> modelServiceMap;
    private final AiModelConfig aiModelConfig;

    @Autowired
    public AiModelFactory(AlibabaAiModelServiceImpl alibabaAiModelService,
                         DeepSeekAiModelServiceImpl deepSeekAiModelService,
                         AiModelConfig aiModelConfig) {
        this.aiModelConfig = aiModelConfig;
        this.modelServiceMap = new HashMap<>();
        modelServiceMap.put(AiModelType.ALIBABA.getCode(), alibabaAiModelService);
        modelServiceMap.put(AiModelType.DEEPSEEK.getCode(), deepSeekAiModelService);
    }

    /**
     * 根据模型名称获取AI模型服务
     * @param modelName 模型名称 (alibaba 或 deepseek)
     * @return AI模型服务实例
     */
    public AiModelService getAiModelService(String modelName) {
        if (modelName != null && modelServiceMap.containsKey(modelName)) {
            return modelServiceMap.get(modelName);
        }
        // 如果未指定模型名称或模型名称不存在，使用默认模型
        return modelServiceMap.get(aiModelConfig.getDefaultModel());
    }

    /**
     * 根据输入内容自动选择AI模型服务
     * 策略：检测输入内容中是否包含大量中文
     * @param input 输入内容
     * @return AI模型服务实例
     */
    public AiModelService autoSelectAiModelService(String input) {
        // 检测输入内容是否包含中文
        boolean containsChinese = containsChinese(input);

        // 如果包含中文，优先使用阿里模型
        if (containsChinese) {
            return modelServiceMap.getOrDefault("alibaba", getDefaultAiModelService());
        } else {
            // 否则使用DeepSeek模型
            return modelServiceMap.getOrDefault("deepseek", getDefaultAiModelService());
        }
    }

    /**
     * 检测字符串是否包含中文
     * @param str 待检测字符串
     * @return 是否包含中文
     */
    private boolean containsChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        // 匹配中文字符的正则表达式
        Pattern chinesePattern = Pattern.compile("[\u4e00-\u9fa5]");
        return chinesePattern.matcher(str).find();
    }

    /**
     * 获取默认AI模型服务
     * @return 默认AI模型服务实例
     */
    public AiModelService getDefaultAiModelService() {
        return modelServiceMap.get(aiModelConfig.getDefaultModel());
    }
}